// 登陆管理后台
const config = require('./config')
const puppeteer = require('puppeteer'); 
const {
    getElementPosition,
    selectAndClick,
    getLastDialog,
    selectInputAddEdit,
    clickByText,
    resetInputValue,
    selectByIndexAndType,
    selectAndType,
    selectDefaultDate,
    selectFirstItem,
    xPathAndClick,
    clickDialogHeader,
    getStartTime,
    clickFirstSelectDropdownItem,
    getLastSelectDropdown,
    selectDate,
    getRequestBody,
    uploadFile,
    getStorage,
    removeAllStorage,
    selectByText
} = require('./utils');
const { liveAddr } = require('./config');

function autoLogin () {
    return new Promise(async (resolve, reject) => {
        const browser = await puppeteer.launch({
            headless: false,
            // 视口大小
            defaultViewport: {
                width: 1920,
                height: 1080
            },
            // 调节窗口大小
            args: [
                '--window-size=1920,1080'
            ]
        })
        const page = await browser.newPage()

        await page.goto(`${config.env === 'prod' ? 'https' : 'http'}://${config.env}.ykt100.com/console/#/login`)
        await page.waitForSelector('.login-form')
        let userInput = await page.$('.login-form input:nth-child(1)')
        await userInput.type(config.loginName)
        let pwdInput = await page.$('input[placeholder=请输入密码]')
        await pwdInput.type(config.loginPwd)
        let submitBtn =  await page.$('.login-main button')
        await submitBtn.click()

        // 选择左边的menu
        // 等待某个元素加载出来，再去执行点击事件
        await page.waitForSelector('.icon-zhibo')
        const subjectMenu =  await page.$('.icon-msnui-supervise')
        await subjectMenu.click()

        await page.$eval('.el-submenu.is-opened .el-menu-item > span', el => {
            if (el.innerText === '课程管理') {
                el.click()
            }
        });
        
        // 点击新增课程
        await page.waitForSelector('.avue-crud__menu button')
        const addProjectBtn =  await page.$('.avue-crud__menu button')
        addProjectBtn.click()
       
        // 选择年级
        await page.waitForSelector('.el-dialog input[placeholder=请选择年度]')
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择年度]', 4) // 选择2021
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择年级]')
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择学期]')
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择科目]')
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择课程级别]')
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择课程类型]')
        await selectInputAddEdit(page, '.el-dialog input[placeholder=请输入课程后缀]', config.postfix || 'auto' + Date.now())
        await selectInputAddEdit(page, '.el-dialog input[placeholder^=请输入总学时]', config.learnTime)
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择所属地区]')
        await selectFirstItem(page, '.el-dialog input[placeholder=请选择班级类型]')
        // 这里要注意，1. 如果placeholder有()的时候会选择不到 2. 如果input框为text，后面要字符串的888，不能是数字的888

        // 点击保存
        await selectAndClick(page, '.el-dialog[aria-label=新增] button.el-button--primary')

        await page.waitForTimeout(2000)

        // 点击详情
        await selectAndClick(page, '.el-table .el-table__row:nth-of-type(1) .el-icon-document')

        await page.waitForTimeout(4000)

        // 点击新增章节 
        // await selectAndClick(page, '.avue-crud__menu button:nth-of-type(1)')
        await xPathAndClick(page, '//*[@id="pane-base_info"]/div[4]/div[3]/div/div/div/div[2]/div[1]/button[1]')

        await page.waitForSelector('.el-dialog input[placeholder$=章节名称]')
        // 新增章节 - 输入章节名称
        await selectInputAddEdit(page, '.el-dialog input[placeholder$=章节名称]', config.chapter)
        
        // 点击保存
        var lastDialog = await getLastDialog(page)
        await selectAndClick(lastDialog, '.dialog-footer button:nth-of-type(1)')

        // 等页面的table渲染出来
        // await getRequestBody(page, 'http://uat.ykt100.com/api/cc/chapter/page', true)
        await page.waitForTimeout(2000)

        // 点击班级
        await selectAndClick(page, '#tab-class')

        await page.waitForTimeout(4000)

        // 点击新增班级
        await xPathAndClick(page, '//*[@id="pane-class"]/div/div[2]/div[2]/div[1]/button')

        await page.waitForTimeout(2000)
        var lastDialog = await getLastDialog(page)
        config.className = 'autoClassName' + Date.now()
        await selectInputAddEdit(lastDialog, 'input[placeholder$=班级名称]', config.className)
        await selectInputAddEdit(lastDialog, 'input[placeholder$=价值]', config.worth)
        // await selectAndClick(lastDialog, 'input[placeholder=选择日期时间]')
        await selectAndType(lastDialog, 'input[placeholder=选择日期时间]')
        await selectDefaultDate(page)

        await selectByIndexAndType(lastDialog, 'input[placeholder=选择日期时间]', 2)
        // await selectAndType(lastDialog, 'label[for=endDate] + div > .el-date-editor')
        await selectDefaultDate(page)

        // 选择期数
        await selectFirstItem(page, '.el-dialog input[placeholder$=期数]', 2)

        // 点击保存
        await clickByText(lastDialog, '.dialog-footer button span', '保 存')

        // 存在刷新操作
        await page.waitForTimeout(4000)
        await clickByText(page, '.el-table .cell button span', '查看详情')

        await page.waitForTimeout(4000)
        await clickByText(page, '.chapter-container button span', '编辑')

        var lastDialog = await page.$('.el-dialog[aria-label=编辑课次]')

         // 要先把日期给清除掉
        await resetInputValue(page, '.el-dialog[aria-label=编辑课次] input[placeholder=请选择开课日期]')
        // 如果有传开课日期就使用开课日期，要么就使用当前日期为开课日
        const classStartDate = config.startDate || new Date().toLocaleDateString().replace(/\//g, '-')
        await selectAndType(lastDialog, 'input[placeholder=请选择开课日期]')
        await selectDate(page, classStartDate)
    
        // 计算开课时间
        const startTime = getStartTime(config.startTimeDelay)
        // fix: 输入14:12的时候，有时候会把14变成4， 所以前面加了个空格
        await selectAndType(lastDialog, 'input[placeholder=请选择上课时间]', ' ' + startTime)
        await clickDialogHeader(lastDialog)

        // 下课时间功能添加
        await selectAndType(lastDialog, 'input[placeholder=请选择下课时间]', ' ' + '23:59')
        await clickDialogHeader(lastDialog)

        await selectAndType(lastDialog, 'input[placeholder=请选择对应地区的授课讲师]')
        await page.waitForTimeout(400)
        // await clickFirstSelectDropdownItem(page)
        await clickByText(page, '.el-select-dropdown__item span', config.teacherName)

        await clickByText(page, '.el-dialog[aria-label=编辑课次] .submit button span', '确认提交')
        await page.waitForTimeout(4000)
        await clickByText(page, '.el-table td button span', '创建直播')
        await page.waitForTimeout(1500)
        await clickByText(page, '.el-dialog .dialog-footer button span', config.liveType)
        await page.waitForTimeout(1000)
        await clickByText(page, '.el-dialog .el-radio__label', config.liveAddr)
        await clickByText(page, '.el-dialog .dialog-footer button span', '确定')
        await page.waitForTimeout(3000)

        // 开放课程
        await clickByText(page, '.detail-info button span', '未开放')
        await page.waitForTimeout(1000)

        await clickByText(page, '.el-message-box__wrapper .el-message-box__btns button span', '确定')
        await page.waitForTimeout(1000)
        console.log('直播创建成功~')

        // 开始去查看具体的直播id
        await selectAndClick(page, '.icon-zhibo')

        await page.waitForTimeout(1000)

        await clickByText(page, '.avue-left .el-menu-item span', '盐直播')

        // 搜索框里面填写老师的姓名
        await page.waitForSelector('input[placeholder=讲师姓名]')
        await selectInputAddEdit(page, 'input[placeholder=讲师姓名]', config.teacherName)

        // 点击搜索
        await selectAndClick(page, '.el-form .el-icon-search')

        var tableData = await getRequestBody(page, `${config.env === 'prod' ? 'https' : 'http'}://${config.env}.ykt100.com/api/alive/liveinfo/findLiveInfoList`,  true)
        var tableList = tableData.data.records
        const liveId = tableList[0].id
        const token = await getStorage(page, 'localStorage', 'salt-classes-token')
        console.log('token:', token)
        const teacherLiveUrl = `${config.env === 'prod' ? 'https' : 'http'}://${config.env}.ykt100.com/play/t.html?id=${liveId}`
        const studentLiveUrl = `${config.env === 'prod' ? 'https' : 'http'}://${config.env}.ykt100.com/play/student.html?id=${liveId}`
        console.log(`老师直播链接：${teacherLiveUrl}`)
        console.log(`学生直播链接：${studentLiveUrl}`)
        // await removeAllStorage(page)
        // await page.goto(`${config.env === 'prod' ? 'https' : 'http'}://${config.env}.ykt100.com/console`)
        // userInput = await page.$('.login-form input:nth-child(1)')
        // await userInput.type(config.teacherPhone)
        // pwdInput = await page.$('input[placeholder=请输入密码]')
        // await pwdInput.type(config.loginPwd)
        // submitBtn =  await page.$('.login-main button')
        // await submitBtn.click()

        // await page.waitForSelector('.icon-jiaoseguanli')
        // await clickByText(page, '.avue-left .el-submenu__title span', '讲师工作台')
        // await sleep.msleep(300)
        // await clickByText(page, '.avue-left .el-menu-item span', '我的课程')

        // await page.waitForSelector('.course-list input[placeholder=请输入班级名称]')
        // await selectAndType(page, 'input[placeholder=请输入班级名称]', config.className)
        // await page.keyboard.press("Enter",{delay:50});
        // await sleep.sleep(1)
        // await clickByText(page, '.card-title p', config.className)
        // await sleep.sleep(1)
        // await page.waitForSelector('.teacher-live-detail.avue-view')

        // // await getRequestBody(page, 'http://uat.ykt100.com/api/cc/teacher/myOfferingChapter?', true)
        // await sleep.sleep(2)
        // await selectAndClick(page, '.teacher-live-detail .el-tooltip')
        // await sleep.msleep(300)
        // await uploadFile(page)
    })
}

autoLogin()

module.exports = autoLogin

// 1622879773195